/**
* 根据图片位置信息载入图片
*/
package com.tudou.top2.controller
{
	import com.tudou.top2.events.PictEvent;
	import com.tudou.top2.model.AdDataModel;
	import com.tudou.top2.model.AdUrlModel;
	import com.tudou.top2.model.PictUrlModel;
	import com.tudou.top2.model.PictsDataModel;
	import com.tudou.top2.model.SmallBox;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	
	public class LoadPicts extends EventDispatcher
	{
		//存储所有加载完成的图片和标题
		private var pictsDataModel:PictsDataModel;
		//存储加载完成的广告图片和图标
		private var adDataModel:AdDataModel;
		//存储视频图片的各种信息 内存储类型为PictUrlModel
		private var pictsUrl:Array;
		//存储广告的各种信息
		private var adUrl:AdUrlModel;
		//加载顺序队列
		private var loadQueue:Array;
		
		private var countSmall:int = 0;
		
		private var countBig:int = 0;
		
		private var countAdPicts:int = 0;
		
		private var loader:Loader;
		
		private var urlRequest:URLRequest;
		//载入图片数组的总长度
		private var arrayLength:uint;

		private static const smallLimit:int = 4;
		
		private static const bigLimit:int = 1;
		
		
		public function LoadPicts()
		{
			pictsDataModel = new PictsDataModel();
			adDataModel = new AdDataModel();
			loadQueue = new Array();
			addEventListener(PictEvent.LOAD_RIGHT_NOW, loadNow);
		}
		
		public function loadNow(pe:PictEvent):void
		{
			var index:int = pe.index;
			//判断是否在待加载队列
			if(loadQueue.indexOf(index) > 0)
			{
				trace("loadNow" + index);
				arrangeQueue(index);
//				loadOnePict(pictsUrl[index].bigPicUrl);
			}
			else
			{
				trace("The " + index + " is loading or loaded now!");
			}
			
		}
		
		//开始载入，传入取得的URl数组
		public function load(pictsUrl:Array, adUrl:AdUrlModel):void
		{
			this.pictsUrl = pictsUrl;
			this.adUrl = adUrl;
			adUrl = adUrl;
			
			arrayLength = pictsUrl.length;
			
			pictsDataModel.arrayLength = arrayLength;
			trace("arryLength = " + arrayLength);
			
			process();
			startLoad();
		}
		//处理 title link textColor
		private function process():void
		{
			var urlM:PictUrlModel;
			for(var i:int=0; i<4; i++)
			{
				urlM = pictsUrl[i];
				var smlBox:SmallBox = pictsDataModel.smallBoxes[i];
				smlBox.textColor = ASColor(urlM.textColor);
				smlBox.title = urlM.title;
			}
			for(i=0; i<arrayLength; i++)
			{
				urlM = pictsUrl[i];
				pictsDataModel.links[i] = urlM.link;
				pictsDataModel.bigTitles[i] = urlM.bigTitle;
				pictsDataModel.bigTextColors[i] = ASColor(urlM.bigTextColor);
			}
			adDataModel.adLink = adUrl.adLink;
		}
		//变为AS3的颜色
		private function ASColor(jsColor:String):uint
		{
			//进行数据校验
			return uint("0x" + jsColor.substring(1));
		}
		
		private function startLoad():void
		{
			//从小图第一张开始
			var url:PictUrlModel = PictUrlModel(pictsUrl[0]);
			loadOnePict(url.smallPicUrl);
		}
		
		private function loadAdPicts():void
		{
			//有广告则加载
			if(adUrl.hasAd)
			{
				adDataModel.hasAd = true;
				loadOnePictFunErr(adUrl.adIconUrl, adIconComplete, adIconErr);
				loadOnePictFunErr(adUrl.adPictUrl, adPictComplete, adPictErr);
			}
			//没广告
			else
			{
				adDataModel.hasAd = false;
			}
		}
		
		private function adIconComplete(e:Event):void
		{
			countAdPicts++;
			var disp:DisplayObject = DisplayObject(e.target.content);
			adDataModel.addToIcon(disp);
			
			if(countAdPicts == 2)
			{
				adDataModel.isLoaded = true;
				dispatchEvent(new PictEvent(PictEvent.LOAD_ALL_ADPICTS_FINISHED));
			}
		}
		private function adIconErr(ioe:IOErrorEvent):void
		{
			trace(ioe);
		}
		private function adPictComplete(e:Event):void
		{
			countAdPicts++;
			var disp:DisplayObject= DisplayObject(e.target.content);
			adDataModel.addToPict(disp);
			
			if(countAdPicts == 2)
			{
				adDataModel.isLoaded = true;
				dispatchEvent(new PictEvent(PictEvent.LOAD_ALL_ADPICTS_FINISHED));
			}			
		}
		private function adPictErr(ioe:IOErrorEvent):void
		{
			trace(ioe);
		}
		
		private function loadOnePict(url:String):void
		{
			loadOnePictFun(url, pictComplete);
		}
		
		private function loadOnePictFun(url:String, fun:Function):void
		{
			loadOnePictFunErr(url, fun, ioErrorHandler);
		}
		
		private function loadOnePictFunErr(url:String, fun:Function, err:Function):void
		{
			loader = new Loader();
			urlRequest = new URLRequest(url);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, fun);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, err);
			loader.load(urlRequest, new LoaderContext(true));
		}
		
		private function ioErrorHandler(ioe:IOErrorEvent):void
		{
//			throw ioe + "Mybe the url is wrong!";
			trace(ioe);
			pictComplete(new Event(""));
		}
		
		private	var cur:int;
		
		private function pictComplete(e:Event):void
		{
			//数组中每一个Model
			var pictUrlModel:PictUrlModel;
			var loderInfo:LoaderInfo;
			var bmp:Bitmap = null;
			if(e != null)
			{
				loderInfo = e.target as LoaderInfo;
				if(loderInfo != null)
				{
					bmp = Bitmap(loderInfo.content);
				}
			}
			//未加载完四张小图
			if(countSmall < smallLimit-1)
			{
				//放入数据
				pictsDataModel.addSmallPict(countSmall++, bmp);

				pictUrlModel = pictsUrl[countSmall];
				loadOnePict(pictUrlModel.smallPicUrl);
			}
			//加载完第四张图
			else if(countSmall == smallLimit-1)
			{
				pictsDataModel.addSmallPict(countSmall++, bmp);
				//随机加载的第一张大图
				cur = randomIndex();
				//重新排列
				arrangeQueue(cur);
				nextQueueElem();
				pictUrlModel = pictsUrl[cur];
				loadOnePict(pictUrlModel.bigPicUrl);			
			}
			//已加载完成第一张大图
			else if(countBig < bigLimit)
			{
				pictsDataModel.addBigPict(cur, bmp);
				//加载广告图片
				loadAdPicts();
				countBig++;
				//下一张
				cur = nextQueueElem();
				trace(cur, "====", loadQueue);
				pictUrlModel = pictsUrl[cur];
				loadOnePict(pictUrlModel.bigPicUrl);
				//四小一大加载完成，发送事件
				dispatchEvent(new PictEvent(PictEvent.LOAD_PICT_FINISHED));
			}
			else if(countBig < arrayLength-1)
			{
				pictsDataModel.addBigPict(cur, bmp);
				countBig++;
				cur = nextQueueElem();
				trace(cur, "====", loadQueue);
				
				pictUrlModel = pictsUrl[cur];
				loadOnePict(pictUrlModel.bigPicUrl);
			}
			//加载完成最后一张大图
			else
			{
				pictsDataModel.addBigPict(cur, bmp);
				countBig++;
				dispatchEvent(new PictEvent(PictEvent.LOAD_ALL_PICTS_FINISHED));
				trace(PictEvent.LOAD_ALL_PICTS_FINISHED);
			}
		}
		
		private function randomIndex():int
		{
			var i:int = pictsDataModel.currentPict = Math.random()*arrayLength;
			trace("random = " + i);
			loadQueue.push(i);
			for(var j:int=0; j<arrayLength-1; j++)
			{
				loadQueue.push(nextIndex(loadQueue[j]));
			}
			trace(loadQueue);
			return i;
		}
		
		private function nextIndex(cur:int):int
		{
			var i:int = (cur+1)%arrayLength;
			trace("next = " + i);
			return i;
		}
		//重新排列队列
		private function arrangeQueue(e:int):void
		{
			var index:int = loadQueue.indexOf(e);
			var a:Array = loadQueue.splice(0, index);
			loadQueue = loadQueue.concat(a);
			trace("--->>", loadQueue);
		}
		
		private function nextQueueElem():int
		{
			return loadQueue.shift();
		}
		
		public function get pictsData():PictsDataModel
		{
			return pictsDataModel;
		}
		
		public function get adData():AdDataModel
		{
			return adDataModel;
		}
		
	}
}